package filepro;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;

/**
 * 文件合并器-字节流
 * @author small瑞
 */
public class FileCombiner {

    private Comparator<File> comparator ;

    private FileCombiner(){}

    public static FileCombiner getInstance(Comparator<File> comparator){
        FileCombiner fileCombiner = new FileCombiner();
        fileCombiner.comparator = comparator;
        return fileCombiner;
    }

    public  static FileCombiner getInstance(){
        Comparator<File> comparator = Comparator.comparing(File::getName);
        return getInstance(comparator);
    }

    public void combine(File path , File dest) throws IOException {
        if(!path.isDirectory()){
            throw new RuntimeException("不是一个文件夹!");
        }
        if(!dest.exists()){
            dest.createNewFile();
        }
        FileOutputStream outputStream = new FileOutputStream(dest,true);
        File[] files = path.listFiles();
        //排序
        Arrays.sort(files,this.comparator);
        //byte[] bytes = new byte[12];
        for(File cur : files){
            FileInputStream fileInputStream = new FileInputStream(cur);
            byte[] bytes = fileInputStream.readAllBytes();
            outputStream.write(bytes);
//            while(fileInputStream.read(bytes)!=-1){
//                int j = fileInputStream.read(bytes);
//                outputStream.write(bytes,0,j);
//            }
            fileInputStream.close();
        }
        outputStream.flush();
        outputStream.close();
    }

    public static void main(String[] args) throws IOException{
//        File path = new File("G:/IO");
//        File dest = new File("G:/IO/牵丝戏合集.txt");
        File path = new File("G:/IO/mmp");
        File dest = new File("G:/IO/mmp/合集.mp3");
        FileCombiner fileCombiner = FileCombiner.getInstance();
        fileCombiner.combine(path,dest);
        System.out.println(Arrays.toString(path.list()));
    }

}
